package  
{
	import connect.Jsfl;
	import fl.controls.CheckBox;
	import fl.controls.ComboBox;
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;
	import flash.system.System;
	import flash.text.TextField;
	import mx.graphics.codec.PNGEncoder;
	import mx.utils.Base64Encoder
	import event.DocumentEvent;
	import utils.util;
	
	/**
	 * ...
	 * @author chitose
	 */
	public class Main extends Sprite
	{
		public var documentTextField:TextField;
		public var cjsPathTextField:TextField;
		public var jsonPathTextField:TextField;
		public var spPathTextField:TextField;
		public var fpPathTextField:TextField;
		public var btnSave:SimpleButton
		//public var btnRe:SimpleButton
		public var btnExport:SimpleButton
		public var btnBase64:SimpleButton;
		public var btnJump:SimpleButton;
		//public var baseCode:ComboBox
		public var cjsCB:CheckBox
		public var fpCB:CheckBox
		public var spCB:CheckBox
		public var convertCB:CheckBox
		
		private var arr:Array = [];
		private var hostPath:String;
		private var version:String;
		private var documentEvent:DocumentEvent = new DocumentEvent();
		
		public function Main() 
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.addEventListener(Event.RESIZE, resize);
			
			btnSave.addEventListener(MouseEvent.CLICK, saveData);
			//btnRe.addEventListener(MouseEvent.CLICK, getData);
			btnExport.addEventListener(MouseEvent.CLICK, export);
			btnBase64.addEventListener(MouseEvent.CLICK, base64enc);
			btnJump.addEventListener(MouseEvent.CLICK, jump);
			
			cjsPathTextField.addEventListener(Event.CHANGE,changed)
			jsonPathTextField.addEventListener(Event.CHANGE,changed)
			spPathTextField.addEventListener(Event.CHANGE,changed)
			fpPathTextField.addEventListener(Event.CHANGE,changed)
			cjsCB.addEventListener(Event.CHANGE,changed)
			fpCB.addEventListener(Event.CHANGE,changed)
			spCB.addEventListener(Event.CHANGE,changed)
			convertCB.addEventListener(Event.CHANGE,changed)
			
			documentEvent.addEventListener(DocumentEvent.CHANGE, documentChange);
			resize()
		}
		
		private function resize(e:Event = null):void {
			var sw:uint = stage.stageWidth;
			var sh:uint = stage.stageHeight;

			cjsPathTextField.width = sw - (cjsPathTextField.x + 3);
			spPathTextField.width = sw - (spPathTextField.x + 3);
			fpPathTextField.width = sw - (fpPathTextField.x + 3);
			
			jsonPathTextField.width = sw - jsonPathTextField.x * 2;
			jsonPathTextField.height = sh - jsonPathTextField.y - 5 - 20;
			btnBase64.y = jsonPathTextField.y + jsonPathTextField.height + 12;
			documentTextField.width = sw - documentTextField.x * 2;
			btnJump.x = sw - 2;
		}
		
		private function documentChange(e:Event):void {
			getData();
		}
		
		private function getData(e:MouseEvent = null):void {
			var domName:String = Jsfl.getPathURI();
			documentTextField.text = domName;
			var a:int=domName.lastIndexOf("/")+1;
			
			arr = Jsfl.getCreateJSToolkitData();
			cjsPathTextField.text = util.getArrayData(arr, "outputPath", "Toolkit for CreateJSパネルで設定をイジって保存してからやり直してください。");
			
			arr = Jsfl.getCreateJSToolkitData2();
			jsonPathTextField.text = util.getArrayData(arr, "jsonPath", "").split(",").join("\n");
			spPathTextField.text = util.getArrayData(arr, "spPath", domName.substr(a).replace(".fla", "_sp.swf"));
			fpPathTextField.text = util.getArrayData(arr, "fpPath", domName.substr(a).replace(".fla", "_fp.swf"));
			cjsCB.selected = util.getArrayData(arr, "isCjs", "true") == "true";
			fpCB.selected = util.getArrayData(arr, "isFp", "true") == "true";
			spCB.selected = util.getArrayData(arr, "isSp", "true") == "true";
			convertCB.selected = util.getArrayData(arr, "isConvert", "true") == "true";
						
			//index = arr.indexOf("base");
			//if (index == -1) {
			//}else {
				//for (var n:uint = 0; true;n++){
					//if (baseCode.getItemAt(n)) {
						//if (baseCode.getItemAt(n).data == arr[index + 1]) {
							//baseCode.selectedIndex = n;
							//break
						//}
					//}else {
						//break;
					//}
				//}
			//}
		}
		
		private function changed(e):void {
			Jsfl.runJSFL("ToolkitSupporter/toolkitSupporter.jsfl", "change",
				cjsPathTextField.text,
				getJson(),
				spPathTextField.text,
				fpPathTextField.text,
				cjsCB.selected,
				fpCB.selected,
				spCB.selected,
				convertCB.selected);
				//baseCode.selectedItem.data);
		}
		
		private function saveData(e:MouseEvent = null):void { 
			Jsfl.runJSFL("ToolkitSupporter/toolkitSupporter.jsfl", "save");
		}
		
		private function getJson():String {
			var jsontext:String = jsonPathTextField.text.split("\n\r").join(",");
			jsontext = jsontext.split("\n").join(",");
			jsontext = jsontext.split("\r").join(",");
			return jsontext;
		}
		
		private var jsPath:String
		private var htmlPatj:String;
		private var bef:String
		private function export(e:MouseEvent):void {
			if (hasEventListener(Event.ENTER_FRAME)) {
				Jsfl.runJSFL("ToolkitSupporter/cjsCommentOut.jsfl", "rollBack");
				removeEventListener(Event.ENTER_FRAME, weit);
			}
			getData();
			var index:uint = documentTextField.text.lastIndexOf("/")+1;
			var host:String = documentTextField.text.substr(0, index);
			
			var v1:String = fpCB.selected ? fpPathTextField.text : "";
			var v2:String = spCB.selected ? spPathTextField.text : "";
			Jsfl.runJSFL("ToolkitSupporter/multiExporter.jsfl", "exportSWF", v1, v2);
			
			if (cjsCB.selected) {
				if (convertCB.selected) {
					Jsfl.runJSFL("ToolkitSupporter/cjsCommentOut.jsfl", "convert");
				}
				
				jsPath=host + cjsPathTextField.text + documentTextField.text.substr(index).replace(".fla", ".js")
				htmlPatj=host + cjsPathTextField.text + documentTextField.text.substr(index).replace(".fla", ".html")
				bef = Jsfl.getModificationDate(jsPath);
				
				var res:String = Jsfl.exists("CreateJS/jsfl/Publish%20for%20CreateJS.jsfl");
				if (res == "true") {
					version="v1.1"
					Jsfl.trace("v1.1_Publish for CreateJS");
					res=Jsfl.runJSFL("CreateJS/jsfl/Publish%20for%20CreateJS.jsfl");
				}else {
					Jsfl.trace("v1.0_Publish for CreateJS");
					version="v1.0"
					res=Jsfl.runJSFL("Commands/Publish%20for%20CreateJS.jsfl");
				}			
				Jsfl.trace("Toolkit for CraeteJSパネルを開いてください");
				addEventListener(Event.ENTER_FRAME, weit);
			}
		}
		private function weit(e:Event):void {
			var aft:String = Jsfl.getModificationDate(jsPath);
			if (bef != aft) {
				removeEventListener(Event.ENTER_FRAME, weit);
				
				if (convertCB.selected) {
					Jsfl.runJSFL("ToolkitSupporter/cjsCommentOut.jsfl", "rollBack");
				}
				Jsfl.runJSFL("ToolkitSupporter/spritesheet.jsfl", "run", version, jsPath, htmlPatj, getJson(), convertCB.selected);
				Jsfl.runJSFL("ToolkitSupporter/multiExporter.jsfl", "set_spSwf");
				Jsfl.trace("Toolkit Supporterの処理が完了しました。 : Chitose")
			}
		}
		
		private function base64enc(e:MouseEvent):void {
			var str:String = Jsfl.runJSFL("ToolkitSupporter/getImageData.jsfl", "func");
			
			var arr:Array = str.split(",");
			var code:String = "";
			for (var i:uint = 0; i < arr.length; i += 2 ) {
				run(i,arr)
			}
			function run(i:uint,arr):void {
				var name:String = arr[i];
				var path:String = arr[i + 1];
				
				var loader:Loader = new Loader()
				var req:URLRequest = new URLRequest(path);
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, comp);
				loader.load(req)
				function comp(e:Event):void {
					var base64 : Base64Encoder = new Base64Encoder();
					base64.encodeBytes((new PNGEncoder).encode(Bitmap(LoaderInfo(e.currentTarget).content).bitmapData));
					var str:String = base64.toString();
					var a:String = '="data:image/jpeg;base64,' + str.split("\n").join("") + '"';
					code += 'images.' + name + '=new Image();\n';
					code += 'images.' + name + a + ';\n';
					
					System.setClipboard(code);
				}
			}
		}
		
		private function jump(e:MouseEvent):void {
			var req:URLRequest = new URLRequest("http://code.google.com/p/toolkit-supporter/");
			navigateToURL(req, "toolkit");
		}
	}

}